<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { get, post } from '@/utils/service'
import { SERVICE_MOBILEPHONE, VUE_APP_BASE_API } from '@/utils/baseConfig'
import { showNotify } from 'vant' // 可选：根据你的UI库引入提示组件，如 Element-UI, Vant 等
import router from '@/router'
function onClickLeft() {
  window.history.back()
}
const hasRepairState = 1 //是否有售后
const routers = useRouter()
const member = ref({})
const custName = ref('')
const mobilePhone = ref('')
const stepActive = ref(0)
const roomActive = ref(0)
const dateActive = ref(0)
const showHasCarSeriyPicker = ref(false)
const loadingStatus = ref(false)
const entepriseColumns = ref([])
const memberCarInfoColumns = ref([])
const carPlateNo = ref('')
const note = ref('')
//门店选择器
const resultEnterpriseName = ref('')
const enterpriseValue = ref([])
const showEnterprisePicker = ref(false)
const hasCarSeriyName = ref('')
const hasCarSeriyValue = ref([])
const dateArrray = ref([]) //预约时间组
const online = ref({}) //在线预约表单数据

const repairWorkStations = ref([]) //工位列表
const bookingWorkRoleTimes = ref([]) //预约时段
const workStationBookingRoleTimes = ref([])
const bookingRoleTimeSelected = ref({}) //选中预约规则
const bookingDate = ref({}) //选择预约时间
const bookingRoom = ref({}) //选择预约工位

queryCarMasterWechat()
function queryCarMasterWechat() {
  dateArrray.value = getDateArarry().map((item: object) => ({
    ...item,
  }))
  // 异步更新数据
  // setTimeout 仅做示例，真实场景中一般为 ajax 请求
  get('/onlineBookingWechatNew/queryOldCarChangeMemberInfoWechat', {})
    .then((res) => {
      if (res.code === 0) {
        const memberInfo = res.data.member
        member.value = memberInfo
        custName.value = memberInfo.name
        mobilePhone.value = memberInfo.mobilePhone
        const temps = res.data.memberCarInfos
        if (temps != null && temps.length == 1) {
          carSeriyName.value = temps[0].car
          carPlateNo.value = temps[0].carPlate
          online.value.custId = temps[0].custCarId
          online.value.vinCode = temps[0].vinCode
        }
        memberCarInfoColumns.value = temps.map((item: object) => ({
          ...item,
          value: item.dbid,
          text: item.car + '' + item.carPlate,
          carPlate: item.carPlate,
        }))
      } else {
        showNotify({
          type: 'danger',
          message: '获取会员信息失败',
          color: '#FFF',
          background: '#797979',
        })
      }
    })
    .catch((err) => {
      console.log(err)
    })
}
onMounted(async () => {
  try {
    queryEnterprise()
  } catch (error) {
    console.log('onMounted error:' + error)
  }
})
function onEnterpriseConfirm(selectedValues: {}) {
  resultEnterpriseName.value = selectedValues.selectedOptions[0].text
  enterpriseValue.value = []
  enterpriseValue.value.push(selectedValues.selectedOptions[0].value)
  showEnterprisePicker.value = false
}
function onHasCarSeriyConfirm(selectedValues: {}) {
  console.log(selectedValues)
  hasCarSeriyName.value = selectedValues.selectedOptions[0].text
  hasCarSeriyValue.value.push(selectedValues.selectedOptions[0].value)
  carSeriyName.value = selectedValues.selectedOptions[0].car
  carPlateNo.value = selectedValues.selectedOptions[0].carPlate
  showHasCarSeriyPicker.value = false
  online.value.custId = selectedValues.selectedOptions[0].custCarId
  online.value.vinCode = selectedValues.selectedOptions[0].vinCode
}

//品牌选择器
//车系选择
const carSeriyName = ref('')

// 校验函数返回 true 表示校验通过，false 表示不通过

function onFailed(errorInfo: Error | string) {
  console.log('failed', errorInfo)
}
function submitFrm(values: object) {
  try {
    online.value.name = custName.value
    online.value.mobilePhone = mobilePhone.value
    online.value.acceptEnterpriseId = enterpriseValue.value[0] || ''
    online.value.acceptEnterpriseName = values.acceptEnterpriseName
    online.value.carSeriyName = values.carSeriyName
    online.value.carPlate = values.carPlateNo
    online.value.bookingDate = onlineDate.value
    online.value.bookingTime = onlineTime.value
    online.value.bookingDes = note.value
    stepActive.value = 1
    queryBookingWorkStationRole()
  } catch (error) {
    console.log('submit error:' + error)
    loadingStatus.value = false // 隐藏加载状态
    showNotify({ type: 'danger', message: error, color: '#FFF', background: '#797979' })
  } finally {
    loadingStatus.value = false // 隐藏加载状态
  }
}
function saveFrm() {
  const onlineModel = online.value
  loadingStatus.value = true // 显示加载状态
  try {
    post('/onlineBookingWechatNew/saveBookingRepair', onlineModel).then((res) => {
      if (res.code === 0) {
        let previousUrl = routers.options.history.state?.back || window.location.href
        console.log('上一个链接是:', previousUrl)
        let mesg = ''
        if (previousUrl == null || previousUrl.length <= 0) {
          previousUrl = '/'
          mesg = '即将跳转首页...'
        }
        showNotify({ type: 'success', message: res.msg + mesg, duration: 3000 })
        setTimeout(() => {
          routers.push(previousUrl)
        }, 1000)
      } else {
        showNotify({ type: 'danger', message: res.msg, color: '#FFF', background: '#797979' })
      }
    })
  } catch (error) {
    console.log('submit error:' + error)
    loadingStatus.value = false // 隐藏加载状态
    showNotify({ type: 'danger', message: error, color: '#FFF', background: '#797979' })
  } finally {
    loadingStatus.value = false // 隐藏加载状态
  }
}
function queryEnterprise() {
  get('/enterpriseWechatNew/queryWechatSelect', { hasRepairState: hasRepairState }).then((res) => {
    entepriseColumns.value = []
    if (res.code === 0) {
      const data = res.data
      entepriseColumns.value.push(data)
    }
  })
}
function phoneValidator() {
  return /^1\d{10}$/.test(mobilePhone.value)
}
function nameValidator() {
  return /^[\u4e00-\u9fa5]{2,10}$/.test(custName.value)
}
const onlineDate = ref('')
const onlineTime = ref('')

function viewHistoryOnline() {
  router.push('/myOnline')
}
/**功能描述：获取未来14天2周可以预约日期 */
function getDateArarry() {
  const nowDate = new Date()
  const begin = nowDate.getDate() + 1
  const end = begin + 16
  const dateArrray = []
  const days = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  let j = 0
  for (let i = begin; i <= end; i++) {
    const date = new Date(nowDate.getFullYear(), nowDate.getMonth(), i)
    const month = date.getMonth() + 1
    const day = date.getDate()
    const monthDay = month + '/' + (day > 10 ? day : '0' + day)
    const weekDay = days[date.getDay()]
    const bookingDay =
      date.getFullYear() +
      '-' +
      (month > 10 ? month : '0' + month) +
      '-' +
      (day > 10 ? day : '0' + day)
    dateArrray.push({
      monthDay: monthDay,
      weekDay: weekDay,
      bookingDay: bookingDay,
      date: date,
      index: j,
    })
    j++
  }
  return dateArrray
}
/** 选择日期完成步骤 */
function selectDate() {
  const tempBookingRoom = bookingRoom.value
  const tempBookingDate = bookingDate.value
  if (
    tempBookingDate == null ||
    tempBookingDate == undefined ||
    tempBookingDate.bookingDay == undefined ||
    tempBookingDate.bookingDay == ''
  ) {
    showNotify('请选择预约日期')
    return
  }
  if (
    tempBookingRoom == null ||
    tempBookingRoom == undefined ||
    tempBookingRoom.dbid == undefined ||
    tempBookingRoom.dbid == ''
  ) {
    showNotify('请选择预约工位')
    return
  }
  const bookingRoleTimeSelect = bookingRoleTimeSelected.value
  if (
    bookingRoleTimeSelect == null ||
    bookingRoleTimeSelect == undefined ||
    bookingRoleTimeSelect.startTime == undefined ||
    bookingRoleTimeSelect.startTime == ''
  ) {
    showNotify('请选择预约时段')
    return
  }
  stepActive.value = stepActive.value + 1
  console.log(bookingRoleTimeSelect)
  online.value.bookingDate = tempBookingDate.bookingDay
  online.value.workStationId = tempBookingRoom.dbid
  online.value.workStationName = tempBookingRoom.name
  online.value.workRoleTimeId = bookingRoleTimeSelect.workRoleTimeId
  const bookTimeStr = bookingRoleTimeSelect.startTime + ' - ' + bookingRoleTimeSelect.endTime
  online.value.workStationTimeStr = bookTimeStr
  online.value.bookingTime = bookTimeStr
  online.value.workStationTimeId = bookingRoleTimeSelect.workStationTimeId
  onlineTime.value = bookTimeStr
}
/** 返回上一步 */
function backStep() {
  stepActive.value = stepActive.value - 1
}
function queryBookingWorkStationRole() {
  const index = dateActive.value
  const date = dateArrray.value[index]
  bookingDate.value = date //绑定选择邀约日期
  bookingRoleTimeSelected.value = {}
  get('/bookingWechatNew/queryBookingWorkStationRoleWechat', {
    date: date.bookingDay,
    enterpriseId: enterpriseValue.value[0],
  }).then((res) => {
    if (res.code === 0) {
      const bookingWorkStationRole = res.data
      repairWorkStations.value = bookingWorkStationRole.repairWorkStations
      bookingWorkRoleTimes.value = bookingWorkStationRole.bookingWorkRoleTimes
      setTimeout(function () {
        selectWorkStation()
      }, 100)
    } else {
      repairWorkStations.value = []
      bookingWorkRoleTimes.value = []
      setTimeout(function () {
        selectWorkStation()
      }, 100)
      showNotify({
        type: 'danger',
        message: '获取预约工位信息失败，请联系管理员',
        color: '#FFF',
        background: '#797979',
      })
    }
  })
}
function selectWorkStation() {
  //工位选择
  bookingRoleTimeSelected.value = {}
  const temps = bookingWorkRoleTimes.value
  workStationBookingRoleTimes.value = []
  bookingRoom.value = repairWorkStations.value[roomActive.value]
  let i = 0
  temps.forEach((item) => {
    const roleItem = item.repairWorkRoleTime
    let roleTime = item.workStationBookingRoleTimes[roomActive.value]
    roleTime = initRoleTIme(roleItem, roleTime)
    roleTime.index = i
    workStationBookingRoleTimes.value.push(roleTime)
    i++
  })
  console.log('workStationBookingRoleTimes:' + workStationBookingRoleTimes.value)
}
function initRoleTIme(roleItem: object, workStationBookingRoleTime: object) {
  //渲染预约时段
  let classStr = '',
    contentStr = '' + roleItem.timeStr,
    bgColor = ''
  if (workStationBookingRoleTime.bookingState == 1) {
    //可以预约
    classStr = 'enable'
    contentStr = contentStr + '可预约（折扣：' + workStationBookingRoleTime.distancePer + '%）'
    bgColor = ''
  }
  if (workStationBookingRoleTime.bookingState == 2) {
    //不可预约
    classStr = 'disable'
    contentStr = contentStr + '禁止预约'
  }
  if (workStationBookingRoleTime.bookingState == 3) {
    //已经预约
    classStr = 'bookingcreate'
    bgColor = '#c8c9cc'
    contentStr = contentStr + ' 已约定'
  }
  workStationBookingRoleTime.title = contentStr
  workStationBookingRoleTime.classStr = classStr
  workStationBookingRoleTime.bgColor = bgColor
  return workStationBookingRoleTime
}
function selectBookineTime(item: object) {
  //选择预约时段
  if (item == null || item.index == undefined) {
    return
  }
  workStationBookingRoleTimes.value.forEach((tempitem) => {
    if (tempitem.bgColor == '#c82030' && item.bookingState == 1) {
      if (tempitem.bookingState == 1) {
        tempitem.bgColor = ''
        tempitem.classStr = 'enable'
      }
    }
  })
  if (item.bookingState == 1) {
    workStationBookingRoleTimes.value[item.index].bgColor = '#c82030'
    workStationBookingRoleTimes.value[item.index].classStr = 'bookingSelected'
  }
  if (item.bookingState == 1) {
    bookingRoleTimeSelected.value = item
  }
}
</script>
<template>
  <van-nav-bar title="保养预约" left-text="返回" left-arrow @click-left="onClickLeft" />
  <div class="mainContent">
    <van-steps :active="stepActive" active-icon="success" active-color="var(--main-color)">
      <van-step>步骤1、客户信息</van-step>
      <van-step>步骤2、选择预约时间</van-step>
      <van-step>步骤3、预约确认</van-step>
    </van-steps>
  </div>
  <div class="mainContent" :style="stepActive == 0 ? '' : 'display: none;'">
    <div v-if="memberCarInfoColumns.length > 1">
      <van-divider> 已有车辆选择 </van-divider>
      <van-field
        v-model="hasCarSeriyName"
        is-link
        readonly
        name="hasCarValue"
        label="已有车辆"
        placeholder="点击选择车辆"
        @click="showHasCarSeriyPicker = true"
      />
      <van-popup :show="showHasCarSeriyPicker" destroy-on-close position="bottom">
        <van-picker
          :columns="memberCarInfoColumns"
          :model-value="hasCarSeriyValue"
          @confirm="onHasCarSeriyConfirm"
          @cancel="showHasCarSeriyPicker = false"
        />
      </van-popup>
      <br />
    </div>
    <van-form @failed="onFailed" @submit="submitFrm">
      <van-cell-group inset>
        <!-- 通过 pattern 进行正则校验 -->
        <van-field
          v-model="custName"
          required="true"
          label="姓名"
          name="custName"
          placeholder="客户姓名"
          :value="custName"
          :rules="[
            { required: true, message: '请填写姓名' },
            { validator: nameValidator, message: '请输入购车客户姓名,2-10个中文字符' },
          ]"
        />
        <van-field
          v-model="mobilePhone"
          label="联系电话"
          required="true"
          name="mobilePhone"
          placeholder="客户联系电话"
          type="tel"
          :rules="[
            { required: true, message: '请填写手机号码' },
            { validator: phoneValidator, message: '请输入正确的手机号格式', trigger: 'onBlur' },
          ]"
        />
        <van-field
          v-model="resultEnterpriseName"
          is-link
          readonly
          name="acceptEnterpriseName"
          label="门店"
          placeholder="点击选择门店"
          required="true"
          @click="showEnterprisePicker = true"
          :rules="[{ required: true, message: '请选择门店' }]"
        />
        <van-popup :show="showEnterprisePicker" destroy-on-close position="bottom">
          <van-picker
            :columns="entepriseColumns"
            :model-value="enterpriseValue"
            @confirm="onEnterpriseConfirm"
            @cancel="showEnterprisePicker = false"
          />
        </van-popup>
        <van-field
          v-model="carSeriyName"
          required="true"
          label="车型"
          name="carSeriyName"
          placeholder="请输入车型"
          :value="carSeriyName"
          :rules="[
            { required: true, message: '请填写车型' },
            { validator: nameValidator, message: '请输入车型,2-50个中文字符' },
          ]"
        />
        <van-field
          v-model="carPlateNo"
          required="true"
          label="车牌号"
          name="carPlateNo"
          placeholder="请输入车牌号"
          :value="carPlateNo"
          :rules="[
            { required: true, message: '请填写旧车车牌号' },
            { validator: nameValidator, message: '请输入旧车车牌号' },
          ]"
        />
      </van-cell-group>
      <van-cell-group inset>
        <van-field
          v-model="note"
          rows="2"
          autosize
          label="备注"
          type="textarea"
          name="note"
          maxlength="120"
          placeholder="请输入备注"
          show-word-limit
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button
          type="primary"
          style="width: 100%"
          block
          loading-type="spinner"
          loading-text="提交中..."
          native-type="submit"
          >下一步</van-button
        >
      </div>
    </van-form>
  </div>
  <div :style="stepActive == 1 ? '' : 'display: none;'">
    <!--预约日期选中-->
    <van-tabs
      v-model:active="dateActive"
      type="card"
      style="width: 100%"
      title-active-color="#FFF"
      color="#c82030"
      title-inactive-color="#c82030"
      title-style="white-space: normal;"
      @click="queryBookingWorkStationRole"
    >
      <van-tab
        v-for="dateItem in dateArrray"
        :title="dateItem.monthDay + '' + dateItem.weekDay"
        v-bind:key="dateItem.index"
      >
      </van-tab>
    </van-tabs>
    <div style="display: flex; justify-content: flex-start; margin-top: 12px">
      <div style="width: 80px">
        <van-sidebar v-model="roomActive" @click="selectWorkStation"
          ><!--预约工位选中-->
          <van-sidebar-item
            :title="repairWorkStation.name"
            v-for="repairWorkStation in repairWorkStations"
            v-bind:key="repairWorkStation.dbid"
          />
        </van-sidebar>
      </div>
      <div style="width: 100%; padding-left: 12px">
        <van-cell-group title="选择预约时段" v-if="workStationBookingRoleTimes.length > 0">
          <van-cell
            :title="workStationBookingRoleTime.title"
            style="color: var(--main-color)"
            v-for="workStationBookingRoleTime in workStationBookingRoleTimes"
            v-bind:key="workStationBookingRoleTime.dbid"
            :title-class="workStationBookingRoleTime.classStr"
            :style="'background-color:' + workStationBookingRoleTime.bgColor"
            @click="selectBookineTime(workStationBookingRoleTime)"
          />
        </van-cell-group>
        <van-empty
          v-else
          :image="VUE_APP_BASE_API + '/images/vue/noData.png'"
          image-size="100"
          description="无预约时段,门店未开启预约功能"
        />
        <br />
      </div>
    </div>
    <div style="margin: 16px">
      <div style="margin: 16px; display: flex; justify-content: flex-start">
        <div style="width: 120px">
          <van-button type="default" plain @click="backStep">上一步</van-button>
        </div>
        <div style="width: 100%">
          <van-button type="primary" style="" block loading-type="spinner" @click="selectDate"
            >下一步</van-button
          >
        </div>
      </div>
    </div>
  </div>
  <!--保存钱确认-->
  <div class="mainContent" :style="stepActive == 2 ? '' : 'display: none;'">
    <van-cell-group>
      <van-cell title="姓名" :value="online.name" />
      <van-cell title="联系电话" :value="online.mobilePhone" />
      <van-cell title="预约日期" :value="online.bookingDate" value-class="price" />
      <van-cell title="预约时段" :value="online.bookingTime" />
      <van-cell title="预约工位" :value="online.workStationName || '无'" />
      <van-cell title="门店" :value="online.acceptEnterpriseName || '无'" />
      <van-cell title="车型" :value="online.carSeriyName || '无'" />
      <van-cell title="车牌号" :value="online.carPlate || '无'" />
    </van-cell-group>
    <van-cell-group border="false">
      <p style="line-height: 200%">备注</p>
      <div class="" style="font-size: 14px; color: var(--van-text-color-2)">
        {{ online.bookingDes || '无' }}
      </div>
    </van-cell-group>
    <div style="margin: 16px; display: flex; justify-content: flex-start">
      <div style="width: 120px">
        <van-button type="default" plain @click="backStep">上一步</van-button>
      </div>
      <div style="width: 100%">
        <van-button
          block
          type="primary"
          :loading="loadingStatus"
          loading-type="spinner"
          loading-text="提交中..."
          native-type="submit"
          @click="saveFrm"
        >
          提交
        </van-button>
      </div>
    </div>
  </div>
  <van-divider :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }">
    温馨提示
  </van-divider>

  <div class="mainContent" style="margin-bottom: 32px">
    <p style="font-size: 14px">
      若您在预约过程中有任何为题请拨打：<a
        :href="'tel:' + SERVICE_MOBILEPHONE"
        style="color: var(--main-color)"
        >{{ SERVICE_MOBILEPHONE }}</a
      >
    </p>
    <p style="font-size: 14px">
      历史预约记录：<a style="color: var(--main-color)" @click="viewHistoryOnline">点击查看</a>
    </p>
  </div>
</template>

<style></style>
